$(function () {
    /* global WebIM location addChatRecord getCookie */
    var conn = new WebIM.connection({
      isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
      https: typeof WebIM.config.https === 'boolean' ? WebIM.config.https : location.protocol === 'https:',
      url: WebIM.config.xmppURL,
      heartBeatWait: WebIM.config.heartBeatWait,
      autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
      autoReconnectInterval: WebIM.config.autoReconnectInterval,
      apiUrl: WebIM.config.apiURL,
      isAutoLogin: true
    });

    conn.listen({
      onOpened: function (message) { //连接成功回调
        // 如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
        // 手动上线指的是调用conn.setPresence(); 如果conn初始化时已将isAutoLogin设置为true
        // 则无需调用conn.setPresence();             
      },
      onClosed: function (message) {},      //连接关闭回调
      onTextMessage: function (msg) {       //收到文本消息
        //时间和内容提取
        var sourceMsg = msg.sourceMsg.split('%datetime%');
        msg.datetime = sourceMsg[1]?timestampToTimeZh(parseInt(sourceMsg[1])):getCurDatetime();
        msg.sourceMsg = sourceMsg[0];
        //根据用户id查看用户信息
        getUserChatList(msg.from.replace('hx_',''),function(userInfo){
          var reg = new RegExp("(<img.*src=\"\.*?\>)");  //正则表达式
          //匹配查询是否存在图片标签
          msg.nickName = userInfo ? userInfo.name : '';
          msg.photo = userInfo ? userInfo.photo : '';
          //有图片按照图片的方式进行保存
          if(reg.test(msg.sourceMsg)){
              var re = /src="([^"]*)"/g;  //只查找 /ckfinder/userfiles/images/qi_cym.jpg 这段路径
              var arr = re.exec(msg.sourceMsg);
              msg.url = arr[1];
              addChatRecord({
                  type: 2,
                  sourceMsg: msg.sourceMsg,
                  sender: msg.from,
                  accepter: msg.to,
                  isSender: 0,
                  url: msg.url,
                  datetime: msg.datetime,
                  isRead: 1,
                  nickName: msg.nickName,
                  photo: msg.photo
              });
          } else {
              addChatRecord({
                  type: 1,
                  sourceMsg: msg.sourceMsg,
                  sender: msg.from,
                  accepter: msg.to,
                  accepterName: getCookie('name'),
                  isSender: 0,
                  datetime: msg.datetime,
                  isRead: 1,
                  nickName: msg.nickName,
                  photo: msg.photo
              });
          }
          queryList();
        });
      }, 
      onEmojiMessage: function (message) {}, //收到表情消息
      onCmdMessage: function (message) {},      //收到命令消息
      onAudioMessage: function (message) {},    //收到音频消息
      onLocationMessage: function (message) {}, //收到位置消息
      onFileMessage: function (message) {},     //收到文件消息
      onVideoMessage: function (message) {
        var node = document.getElementById('privateVideo');
        var option = {
          url: message.url,
          headers: {
            'Accept': 'audio/mp4'
          },
          onFileDownloadComplete: function (response) {
            var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
            node.src = objectURL;
          },
          onFileDownloadError: function () {
            console.log('File down load error.');
          }
        };
        WebIM.utils.download.call(conn, option);
      }, //收到视频消息
      onPresence: function (message) {}, //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
      onRoster: function (message) {}, //处理好友申请
      onInviteMessage: function (message) {}, //处理群组邀请
      onOnline: function () {}, //本机网络连接成功
      onOffline: function () {}, //本机网络掉线
      onError: function (message) {}, //失败回调
      onBlacklistUpdate: function (list) { //黑名单变动
        // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
        console.log(list);
      },
      onReceivedMessage: function (message) {}, //收到消息送达服务器回执
      onDeliveredMessage: function (message) {}, //收到消息送达客户端回执
      onReadMessage: function (message) {

      }, //收到消息已读回执
      onCreateGroup: function (message) {}, //创建群组成功回执（需调用createGroupNew）
      onMutedMessage: function (message) {} //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
    });

    var options = {
      apiUrl: WebIM.config.apiURL,
      user: 'hx_' + getCookie('userId'),
      pwd: '000000',
      appKey: WebIM.config.appkey
    };
    conn.open(options);

    //根据用户id查询用户详细信息
    function getUserChatList(userId,callback){
      $.post('/antique/api/sysUser/query_user_by_userId',{
        userId:userId
      },function(result){
        callback(result.data);
      });
    }

    function getCurDatetime() {
      var date = new Date();
      var year = date.getFullYear(); //获取当前年份   
      var mon = date.getMonth() + 1; //获取当前月份   
      var da = date.getDate(); //获取当前日   
      var day = date.getDay(); //获取当前星期几   
      var h = date.getHours(); //获取小时   
      var m = date.getMinutes(); //获取分钟   
      var s = date.getSeconds(); //获取秒   
      return year + '年' + mon + '月' + da + '日' + ' ' + h + ':' + m + ':' + s;
    }
    var loading = false; //状态标记
    queryList();
    //下拉刷新
    $("#chat").pullToRefresh().on("pull-to-refresh", function () {
        $("#chat-list-content").html("");
        queryList(function(){
            $("#chat").pullToRefreshDone(); // 重置下拉刷新
        });
    });

    function queryList(callback){
        if (loading) return;
        $("#chat-list-content").empty();
        loading = true;
        /* global template getChatList getMyUnReadRecord*/
        var chatList = getChatList();
        updateChatCount();
        /**for (var i = 0;i < chatList.length;i++){
          
        } */
        if  (chatList && chatList.length > 0)
            $("#chat-list-content").append(template('chat-list', {
                list:chatList
            }));          
        else {
            $("#chat-list-content").append('<div class="row">暂无消息!</div>');
        }        
        $(".weui-cell_swiped").swipeout('open');
        $('.delete-swipeout').click(function () {
          $(this).parents('.weui-cell_swiped').remove();
          var char = $(this).parent().parent().attr('char');
          delChater(char);
          return false;
        });
        $('.close-swipeout').click(function () {
          $(this).parents('.weui-cell_swiped').swipeout('close');
          return false;
        });
        loading = false;
        if (callback)callback();
    }

    var updateLoad = false;
    function updateChatCount(){
      var unReadRecord = getMyUnReadRecord();
      if (updateLoad) return;
      updateLoad = true;
      if (unReadRecord > 0 ){
        $('#chatNoReadCount').show();
        $('#chatNoReadCount').text(unReadRecord);
      } else {
        $('#chatNoReadCount').hide();
      }
      updateLoad = false;
    }
});